/**
 * 公共方法模块
 */
;layui.define(['layer', 'notify'], function (exports) {
    var ly = layui.layer,
        o = layui.jquery,
        u = layui.util,
        t = layui.table,
        notify = layui.notify,
        global = {},
        _cacheTable = 'lay-global-cache',
        _reserved = {
            builderArguments: 'builderArguments',
        };


    var methods = {
        getGlobal: async function () {
            var builderToken = o("#" + _reserved.builderArguments).attr('data-token'),
                builderUrl = o("#" + _reserved.builderArguments).attr('data-url');
            const d = await methods.fetchGetPromise(builderUrl, {
                builderTableToken: builderToken,
                getTableArguments: 1
            }, false);
            if (d.code !== 1) {
                ly.msg('加载失败');
                return false;
            }
            global.token = d.data.token;
            return d.data;
        },
        getEditGlobal: async function () {
            var builderToken = o(".layui-form").attr('data-token');
            if (!builderToken) return '';
            const d = await methods.fetchGetPromise(location.pathname, {
                builderTableToken: builderToken,
            }, false);
            if (d.code !== 1) {
                ly.msg('加载失败');
                return false;
            }
            return d.data;
        },
        /**
         * 加载层
         * @param text
         */
        load: function (text = '加载中....') {
            ly.msg('<div><i class="layui-icon layui-icon-loading-1 layui-anim layui-anim-rotate layui-anim-loop"></i> ' + text + '', {
                shade: 0.8,
                time: 99999
            });
        },
        /**
         * 关闭加载层
         */
        closeLoad: function () {
            ly.closeLast();
        },
        /**
         * 询问层
         * @param text
         * @param callback
         * @param title
         */
        confirm: function (text, callback, title = '请确认') {
            ly.confirm(text, {title: title}, function (index) {
                return callback();
            });
        },
        /**
         * 下载文件
         * @param url
         * @param fileName
         */
        downloadJson: async function (url, fileName) {
            const response = await fetch(url);
            if (!response.ok) throw new Error(`网络错误: ${response.status}`);
            const blob = await response.blob();
            const blobUrl = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = blobUrl;
            a.download = fileName;
            a.style.display = 'none';
            document.body.appendChild(a);
            a.click();
            setTimeout(() => {
                document.body.removeChild(a);
                URL.revokeObjectURL(blobUrl);
            }, 100);
        },
        /**
         * POST请求
         * @param url - url
         * @param data - 提交数据
         * @param callback - 回调函数，可选
         * @param load
         */
        fetchPost: function (url, data, callback, load = true) {
            load ? methods.load() : '';
            data.builderTableToken = global.token;
            o.post(url, data, function (d) {
                load ? methods.closeLoad() : '';
                if (typeof callback === 'function') {
                    return callback(d)
                } else {
                    if (d.code === 1) {
                        d.url ? location.href = d.url : (d.msg ? ly.msg(d.msg, {time: 1000}, function () {
                            location.reload()
                        }) : location.reload());
                    } else {
                        ly.msg(d.msg)
                    }
                }
            });
        },
        /**
         * POST请求 - 节流，默认2秒不重复执行
         * @param url - url
         * @param data - 提交数据
         * @param callback - 回调函数，可选
         */
        fetchPostThrottle: layui.throttle(function (url, data, callback) {
            return methods.fetchPost(url, data, callback);
        }, 2000),

        /**
         * fetch请求 - 节流，默认1秒不重复执行，不支持IE，比较老的浏览器不支持
         * @param url - url
         * @param data - 提交数据
         * @param callback - 回调函数，可选
         */
        fetchThrottle: layui.throttle(function (url, data, success, error) {
            return fetch(url, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(data)
            })
                .then(response => response.json())
                .then(e => {
                    typeof success === 'function' ? success(e) : '';
                })
                .catch(e => {
                    typeof error === 'function' ? error(e) : '';
                });
        }, 1000),

        /**
         * GET请求
         * @param url
         * @param data
         * @param callback
         * @param load
         */
        fetchGet: function (url, data, callback, load = true) {
            load ? methods.load() : '';
            if (!data.hasOwnProperty('builderTableToken')) {
                data.builderTableToken = global.token;
            }
            o.get(url, data, function (d) {
                load ? methods.closeLoad() : '';
                if (typeof callback === 'function') {
                    return callback(d)
                } else {
                    if (d.code !== 1) d.msg ? ly.msg(d.msg) : '';
                }
            });
        },
        /**
         * GET请求 返回一个 Promise
         * @param url
         * @param params
         * @param load
         */
        fetchGetPromise: function (url, params, load) {
            return new Promise((resolve, reject) => {
                methods.fetchGet(url, params, function (d) {
                    resolve(d);
                }, load);
            });
        },
        /**
         * 缓存操作
         */
        cache: {
            get: function (key, table = "") {
                return layui.data(table ? table : _cacheTable)[key];
            },
            set: function (key, value, table = "") {
                layui.data(table ? table : _cacheTable, {key: key, value: value})
            },
            remove: function (key, table = "") {
                layui.data(table ? table : _cacheTable, {key: key, remove: true})
            }
        },
        /**
         * 主动触发事件
         * @param type
         */
        event: {
            click: function (filter, ...callback) {
                return methods.event.getEventFunction('lay-click', filter, ...callback);
            },
            change: function (filter, ...callback) {
                return methods.event.getEventFunction('lay-change', filter, ...callback);
            },
            photo: function (title, val) {
                var data = [];
                val.forEach(function (v, i) {
                    data.push({"alt": title, "pid": i, "src": v,})
                })
                ly.photos({photos: {"title": title, "start": 0, "data": data}, footer: false});
            },
            getEventFunction: function (attr, filter, ...callback) {
                var map = {};
                Array.isArray(filter) ? filter.forEach(function (v, i) {
                    map[v] = getFunction(i);
                }) : map[filter] = getFunction(0);

                function getFunction(i = 0) {
                    return function () {
                        var that = o(this), data = that[0].dataset, index;
                        if (attr === 'lay-change') {
                            var cls = data.key ? data.key : 'lay-this';
                            if (data.hasOwnProperty('checkbox')) {
                                that.hasClass(cls) ? that.removeClass(cls) : that.addClass(cls);
                            } else {
                                that.addClass(cls).siblings().removeClass(cls);
                            }

                        }
                        index = callback.length > 1 ? i : 0
                        typeof callback[index] === 'function' ? callback[index](data, that) : '';
                    }
                }

                u.on(attr, map)
            },

        },
        od: function (title, url, w, offset, h = '') {
            var anim, height = h ? h : '100%'
            switch (offset) {
                case "r":
                    anim = 'slideLeft';
                    break;
                case "l":
                    anim = 'slideRight';
                    break;
                case "b":
                    anim = 'slideUp';
                    break;
                case "t":
                    anim = 'slideDown';
                    break;
            }
            ly.open({
                type: 2,
                offset: offset,
                anim: anim,
                area: [w, height],
                shade: 0.3,
                shadeClose: true,
                id: 'ID-demo-layer-direction-r',
                title: [title, 'font-size:14px;color:#000;text-align: left;font-weight: bold'],
                content: url,
                success: function () {
                    o('.layui-layer-setwin').find('.layui-icon').removeClass('layui-icon-close').addClass('layui-icon-error')
                }
            });
        },
        openTableLayer: function (mixed, callback) {
            mixed = mixed || {};
            mixed.title = mixed.title || '新窗口';
            if (!mixed.hasOwnProperty('url') || !mixed.url) {
                console.error('未指定URL');
                return false;
            }
            mixed.width = mixed.width || '90%';
            mixed.row = mixed.row || false;
            mixed.table = mixed.table || 'builderTable';

            parent.layui.layer.open({
                type: 2,
                title: mixed.title,
                shadeClose: true,
                shade: 0.8,
                area: [mixed.width, o(window).height() < 720 ? '90%' : '720px'],
                content: mixed.url,
                btn: mixed.row ? [] : ['确认', '取消'],
                success: function (layero, index) {
                    if (mixed.row) {
                        var iframeWin = parent.window[layero.find('iframe')[0]['name']];
                        iframeWin.layui.table.on('row(' + mixed.table + ')', function (obj) {
                            parent.layui.layer.close(index);
                            callback(obj.data);
                        })
                    }
                },
                btn2: function (index) {
                    parent.layui.layer.close(index);
                },
                btn1: function (index, layero) {
                    var iframeWin = parent.window[layero.find('iframe')[0]['name']];
                    callback(iframeWin.layui.table.checkStatus(mixed.table).data);
                    parent.layui.layer.close(index);
                },
            })
        },
        openFormLayer: function (title, url, width, p = false, callback = '') {
            var n = p ? parent.layui.layer : ly, jq = p ? parent.layui.jquery : o,
                me = p ? parent.layui.methods : methods,
                ify = p ? parent.layui.notify : notify, area;

            if (Array.isArray(width)) {
                area = width;
            } else {
                area = [width, o(window).height() < 720 ? '80%' : '720px'];
            }

            n.open({
                type: 2,
                title: title,
                shadeClose: true,
                shade: 0.8,
                area: area,
                content: url,
                btn: ['确认', '取消'],
                btn2: function (index) {
                    n.close(index);
                },
                btn1: function (index) {
                    var body = n.getChildFrame('body', index), form = body.find('.layui-form');
                    me.fetchPostThrottle(form.attr('action'), form.serialize(), function (d) {
                        if (callback) {
                            callback(d);
                        } else {
                            d.code === 1 ? ify.success(d.msg, 1000, function () {
                                n.close(index);
                                if (jq(".layui-table-page").length > 0 && !p) {
                                    t.reload('builderTable', {
                                        page: {
                                            curr: jq(".layui-laypage-em").next().text()
                                        },
                                    });
                                } else {
                                    var w = window.frames.frameElement.id.includes('layui-layer-iframe');
                                    w ? location.reload() : parent.location.reload();
                                }
                            }) : ify.error(d.msg)
                        }
                    })
                    return false
                },
            })
        }

    }
    exports('methods', methods)
});